package controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.AutoSiteModel;

import forms.AutoSiteForm;

import entities.AutoSite;

@SuppressWarnings("serial")
public class AutoSiteAddServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		AutoSite autoSite = new AutoSite();
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		request.setAttribute("check", check);
		request.setAttribute("autoSite", autoSite);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/pages/autosite_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		AutoSiteModel autoSiteModel = AutoSiteModel.getInstance();
		AutoSite autoSite = new AutoSite();
		
		//Get value form and check valid
		TreeMap form = AutoSiteForm.checkValid(request, autoSite);
		autoSite =(AutoSite) form.get("autoSite");
		TreeMap<String, String>  check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			autoSite.setId(IdUniqueHelper.getId());
			autoSiteModel.insert(autoSite);
			request.setAttribute("success", "Add success site " + autoSite.getUrl());
			autoSite = new AutoSite();
		}
		
		request.setAttribute("check", check);
		request.setAttribute("autoSite", autoSite);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/pages/autosite_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}